package com.yneusoft.manage.aspect;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yneusoft.dao.entity.Department;
import com.yneusoft.dao.entity.DepartmentState;
import com.yneusoft.dao.entity.Staff;
import com.yneusoft.dao.entity.StaffState;
import com.yneusoft.dao.mapper.StaffManageMapper;
import com.yneusoft.manage.model.param.SaveStaffParam;
import com.yneusoft.manage.model.param.UpdateDepartmentStateParam;
import com.yneusoft.manage.model.param.UpdateStaffStateParam;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Aspect
@Component
@Slf4j
public class StaffHttpAspect {
    @Resource
    private StaffManageMapper staffManageMapper;

    @Pointcut(value ="execution(public * com.yneusoft.manage.controller.StaffManageController.saveStaff(..))" )
    public void staff(){};

    @Before("staff()")
    public String getJobNumber(){
        LocalDateTime date1 = LocalDateTime.now();
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMdd");
        String date2Str = formatter2.format(date1);//当天日期

        LambdaUpdateWrapper<Staff> wrapper = new LambdaUpdateWrapper<>();
        int b= staffManageMapper.selectCount(wrapper);
        log.info("---->"+b);

        String a = String.format("%04d", b);
        String jobNumber = date2Str + a;
        log.info("----员工工号>"+jobNumber);

        return jobNumber;

    }
    @Before("staff()")
    public void getState(JoinPoint joinPoint) {
        Object[] list = joinPoint.getArgs();
        for(Object obj :list){
            if(obj instanceof SaveStaffParam){
                SaveStaffParam param = (SaveStaffParam) obj;
                StaffState staffState = StaffState.dataMap.get(1);
                param.setStateId(staffState.getId());
                param.setStateName(staffState.getName());
            }
        }
    }

    @Before("execution(public * com.yneusoft.manage.controller.StaffManageController.updateStaffState(..))")
    public void changeStaffState(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        UpdateStaffStateParam param= (UpdateStaffStateParam) args[0];
        LambdaQueryWrapper<Staff> wrap=new LambdaQueryWrapper<>();
        wrap.eq(Staff::getAid,param.getAid());
        Staff staff=staffManageMapper.selectOne(wrap);
        StaffState staffState;
        if (staff.getStateId()==0){
            staffState=StaffState.dataMap.get(1);
        }else {
            staffState=StaffState.dataMap.get(0);
        }
        param.setStateId(staffState.getId());
        param.setStateName(staffState.getName());
    }

}
